﻿#include "slist.h"

SListNode* BuySListNode(SLTDateType x)
{
	SListNode* ps = malloc(sizeof(SListNode));
	if (ps == NULL)
	{
		perror("BuySListNode::malloc");
		exit(1);
	}
	ps->data = x;
	ps->next = NULL;
	return ps;
}

void SListPushBack(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* newnode = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = newnode;
		return;
	}
	SListNode* pucr = *pplist;
	while (pucr->next)
	{
		pucr = pucr->next;
	}
	pucr->next = newnode;
}

void SListPrint(SListNode* plist)
{
	while (plist)
	{
		printf("%d->", plist->data);
		plist = plist->next;
	}
	printf("NULL\n");
}

void SListPushFront(SListNode** pplist, SLTDateType x)
{

	assert(pplist);
	SListNode* newnode = BuySListNode(x);
	if (*pplist != NULL)
	{
		newnode->next = *pplist;
	}
	*pplist = newnode;
}

void SListPopBack(SListNode** pplist)
{
	assert(pplist && *pplist);
	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
		return;
	}
	SListNode* pucr = *pplist;
	while (pucr->next->next)
	{
		pucr = pucr->next;
	}
	free(pucr->next);
	pucr->next = NULL;
}

void SListPopFront(SListNode** pplist)
{
	assert(pplist && *pplist);
	
	SListNode* pucr = (*pplist)->next;
	free(*pplist);
	*pplist = pucr;

}


SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	//assert(plist);
	while (plist)
	{
		if (plist->data == x)
			return plist;
		plist = plist->next;
	}

	return plist;
}

void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	assert(pos);
	SListNode* Newnode = BuySListNode(x);
	Newnode->next = pos->next;
	pos->next = Newnode;

}


void SListEraseAfter(SListNode* pos)
{

	assert(pos && pos->next);
	SListNode* pcur = pos->next->next;
	free(pos->next);
	pos->next = pcur;

}

void SLTInsert(SListNode** pphead, SListNode* pos, SLTDateType x)
{

	assert(pphead && *pphead && pos);
	SListNode* Newnode = BuySListNode(x);
	SListNode* prev = *pphead;
	if (prev != pos)
	{
		while (prev->next != pos)
		{
			prev = prev->next;

		}
		prev->next = Newnode;
		
	}
	else
	{
		*pphead = Newnode;

	}
	
	Newnode->next = pos;
}


void SLTErase(SListNode** pphead, SListNode* pos)
{
	assert(pphead && *pphead && pos);
	SListNode* prev = *pphead;

	if (prev != pos)
	{
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
	}
	else
	{
		*pphead = pos->next;
	}
	free(pos);

}

void SLTDestroy(SListNode** pphead)
{
	assert(pphead && *pphead);
	SListNode* pcur= *pphead;
	while (pcur)
	{
		pcur = pcur->next;
		free(*pphead);
		*pphead = pcur;
	}

}
